﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.FemaleBeginCommands
{
    public class ProBeginCreateHandler : IRequestHandler<ProBeginCreateCommand, Result>
    {
        private readonly IBaseRepository<ProBegin> probeginbaseRepository;
        private readonly IBaseRepository<SleepInfor> sleepinforbaseRepository;
        private readonly IMapper mapper;

        public ProBeginCreateHandler(IBaseRepository<ProBegin> probeginbaseRepository, IMapper mapper, IBaseRepository<SleepInfor> sleepinforbaseRepository)
        {
            this.probeginbaseRepository = probeginbaseRepository;
            this.sleepinforbaseRepository = sleepinforbaseRepository;
            this.mapper = mapper;
        }

        public async Task<Result> Handle(ProBeginCreateCommand request, CancellationToken cancellationToken)
        {
            var result= new Result() { Code=(int)CodeEnum.add};
            ProBegin proBegin=mapper.Map<ProBegin>(request);
            proBegin.CreateTime = DateTime.Now;
            //后裔期初的添加
            var list = probeginbaseRepository.Add(proBegin);
            if (list > 0)
            {
                //当添加成功时，对后裔档案中的栋舍栏位和在场状态进行修改
                var res=sleepinforbaseRepository.GetAll().FirstOrDefault(x=>x.SleepInforId==request.SleepInforId);
                if(res != null)
                {
                    res.StayStatus = 1;
                    res.RecordcottageId = request.CottagesId;
                    res.FieIdId = request.FieId;
                    sleepinforbaseRepository.Update(res);
                }
            }
            result.Code = list;
            return result;
        }
    }
}
